package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.BookmarkDAO;
import model.Model;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import beans.Bookmark;

import formbeans.BookmarkForm;

/*
 *  Course: S09-15437 - WEB APPLICATION DEVELOPMENT 
 * 	Name: Jiale Huang
 * 	Andrew ID: jialeh
 * 	Date: 2/23/2009
 *  Assignment: Hw4
 */


public class AddCountClickAction extends Action{

	private FormBeanFactory<BookmarkForm> formBeanFactory = FormBeanFactory.getInstance(BookmarkForm.class);
	
	private BookmarkDAO bookmarkDAO;
	
	public AddCountClickAction(Model model){
		
		bookmarkDAO = model.getBookmarkDAO();
	}
	
	@Override
	public String getName() {
		return "addClick.do";
	}

	@Override
	public String perform(HttpServletRequest request) {
		
		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		
		try{
			
			int bid = Integer.parseInt( request.getParameter("bid") );
			
			Bookmark bookmark = bookmarkDAO.lookup(bid);
			
			if(bookmark != null){
				
				if(!bookmarkDAO.updateClickCount(bookmark)){
					
					errors.add("Failed to update click");
				}				 
			}else{
				errors.add("No such bookmark");
			}
			
			return "[out]" + bookmark.getURL();
			
		}catch (DAOException e) {
			errors.add(e.toString());
			return "error.jsp";
		} 
		
	}

}
